import { Component, OnInit, Injectable } from '@angular/core';
import { LoginService } from '../services/login.service';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { Router } from '@angular/router';
import { LocalStorageService } from '../services/local-storage.service';
import { Settings } from '../particle-config/const';
declare var particlesJS:any;
declare var pJSDom: any[];
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {
  validateForm: FormGroup;
  hasUser: boolean;
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }

    this.loginService.login(this.validateForm.get('userName').value, this.validateForm.get('password').value)
      .subscribe(data => {
        if(data != null) {
          this.storage.setObject('currentUser', data);
          console.log('登录时查看信息:', this.storage.getObject('currentUser'))
          switch(data.authority) {
            case 0:
              console.log('普通员工');
              this.storage.set('level', '普通员工');
              this.router.navigateByUrl('employee');
              break;
            case 1:
              console.log('部门经理');
              this.storage.set('level', '部门经理');
              this.router.navigateByUrl('departmentManager');
              break;
            case 2:
              console.log('副总经理');
              this.storage.set('level', '副总经理');
              this.router.navigateByUrl('viceGeneralManager');
              break;
            case 3:
              console.log('总经理');
              this.storage.set('level', '总经理');
              this.router.navigateByUrl('manager');
              break;
            case 4:
              console.log('系统管理员');
              this.storage.set('level', '系统管理员');
              this.router.navigateByUrl('admin');
              break;
            default:
              console.log(data.authority);
              console.log('不存在该用户');
          }
        } else {
          alert("不存在该用户或密码错误");
        }
      })
    
  }

  constructor(
    private fb: FormBuilder,
    private loginService: LoginService,
    private router: Router,
    private storage: LocalStorageService,
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required, Validators.minLength(8) ] ],
      password: [ null, [ Validators.required, Validators.minLength(6) ] ],
      remember: [ true ]
    });
    particlesJS('particles', Settings.ParticlesConfig);
    this.storage.remove('currentUser');
  }

  ngOnDestroy() {
    if (pJSDom && pJSDom.length > 0) {
      // 单页应用的全局对象一直会存在，会产生性能问题
      // 如果存在全局对象则先销毁
      pJSDom[0].pJS.fn.vendors.destroypJS();
      pJSDom = [];
    }
  }

}
